package com.ayit.interceptors;

import com.ayit.utils.JwtUtil;
import com.ayit.utils.ThreadLocalUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;


@Component//把拦截器对象放在IOC容器里
public class LoginInterceptor implements HandlerInterceptor {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //令牌验证
       String token = request.getHeader("Authorization");
        //验证token
        try {
            //从redis中获取相同的Token
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            String redisToken =  operations.get(token);
            if(redisToken == null){
                //token已经失效
                throw new RuntimeException();
            }
            Map<String, Object> claims = JwtUtil.parseToken(token);//返回值类型是JSON
            //把业务数据存储在ThreadLocal中
            ThreadLocalUtil.set(claims);
            return true;//放行
        } catch (Exception e) {
            //http相应状态码为401,是返回给浏览器的
            response.setStatus(401);
            return false;//拦截
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清空ThreadLocal中的数据
        ThreadLocalUtil.remove();
    }
}
